 <?php

/**
 * 客户端基本数据相关接口
 */
class statusController extends base
{
    public function __construct()
    {
        parent::__construct('init');
    }

    /**
     * 数据初始化
     */
    public function doinit()
    {
        $dv = common::request('dv');

        $statusInit = $this->load('client')->statusInit($dv);
        
        if($this->vn >= 2400)
        {
            $uid = $this->uid;
            empty($uid) && $uid = 0;

            $maxCreateNum = $this->load('group')->getMaxGroupNum($uid); // 用户可创建的群组数
            $maxMemberNum = $this->config['group']['maxMember']; // 群组成员最大数量
            
            $statusInit['groupSet'] = compact('maxCreateNum', 'maxMemberNum');
        }

        // 水印列表 - 2.5.5及以上版本支持
        if($this->vn >= 2550)
        {
            $statusInit['watermarks'] = $this->load('watermarks')->getList();
        }

        // 客户端异常数据上传开关 - 2.8.5及以上版本支持
        if($this->vn >= 2850)
        {
            $statusInit['upload_client_odd'] = 1;
        }

        // 装备相关链接 - 2.5.5及以上版本支持
        if($this->vn >= 2550)
        {
            $statusInit['gear_extend'] = array(
                'gear_home_url' => 'http://' . $this->config['host'] . '/show/gearHome',
                'gear_compare_url' => 'http://' . $this->config['host'] . '/show/gearCompare',
                'gear_detail_url' => 'http://' . $this->config['host'] . '/show/gearInfo?gearId={gearId}',
                'gear_set_url' => 'http://' . $this->config['host'] . '/show/gearSet?sid={gearSetId}',
            );
        }

        if($this->vn >= 2820){
            $url_black_list = $this->redis->get(REDIS_PREFIX.'URLBlackList');
            $statusInit['enable_pay_energy'] = $this->config['enable_pay_energy'];
            $statusInit['url_black_list'] = $url_black_list ? json_decode($url_black_list,true) : [];
            $statusInit['marathon'] = $this->load('marathon')->getDisplay();
        }

        if ($this->vn >= 2880) { //体重秤信息
            $statusInit['scaleWeight'] = common::$scaleWeight;
        }
        if($this->vn >= 2890){
            //GPS步幅
            $statusInit['GPSStride'] = array(
                '-150' => array('min' => '0.5', 'max' => '0.7'),
                '150-160' => array('min' => '0.7', 'max' => '0.9'),
                '160-170' => array('min' => '0.9', 'max' => '1.1'),
                '170-180' => array('min' => '1.1', 'max' => '1.2'),
                '180-190' => array('min' => '1.2', 'max' => '1.3'),
                '190-' => array('min' => '1.3', 'max' => '1.4')
            );
            //传感器步幅
            $statusInit['SensorStride'] = array(
                '-150' => '0.7',
                '150-160' => '0.9',
                '160-170' => '1.1',
                '170-180' => '1.2',
                '180-190' => '1.3',
                '190-' => '1.4'
            );
        }
        //是否使用https
        $statusInit['useHttps'] = 1;

        // http白名单 特殊处理
        if($this->uid == 719104)
        {
            $statusInit['useHttps'] = 0;
        }

        //v3.0
        $statusInit['gear'] = array(
            'home_url'=>'http://' . $this->config['host'] . '/show/HomeEquipment',
            'home_search_title'=>'搜索你想要的装备',
            'home_search_url' =>'http://'. $this->config['host'].'/show/gearList?w={w}',
        );

        //被动勋章获得
        if($this->uid && $this->afterVersion('2.9.1','2.9.1')){
            $medal_mod = $this->load('medal');
            $medal_id1 = $medal_mod->addMedalByTag($this->uid,'paidEnergy');
            $medal_id2 = $medal_mod->addMedalByTag($this->uid,'likedPost');
            $medals = [];
            $medal_id1 && $medals[] = $medal_id1;
            $medal_id2 && $medals[] = $medal_id2;
            $statusInit['medal_id'] = $medals;
        }
        
        $statusInit['canChangeFace'] = ( $this->uid && $this->load('user')->canChangeFace($this->uid) ) ?  1 : 0;
        
        $this->result['result'] = $statusInit;
    }
    
    /**
     * 数据初始化
     */
    public function dologout()
    {
        if($this->uid)
        {
            $this->result['result']['is_success'] = $this->load('user')->logout($this->uid);

            // 清空Cookie信息
            setcookie('joggers_u', ' ', time() - 864000 * 365 * 10, '/', '.hupu.com', FALSE, TRUE);
            setcookie('joggers_u', ' ', time() - 864000 * 365 * 10, '/', '.ijoggers.com', FALSE, TRUE);
        }
        else
        {
            $_ENV['error']->getErrors(201);
            exit;
        }
    }

    /**
     * 客户端异常数据上传接口
     */
    public function doclientOdd()
    {
        $this->result['result'] = 0;

        $logParams = [
            'log_type', 'log_content', 'order_id', 
            'restart_sub_process_count', 'restart_host_process_count', 
            'is_bress_quit', 'device_type', 'device_release',
            'sensor', 'home_key_count', 'allsteps', 'costtime', 'mileage', 
            'linemileage', 'start_count', 'continue_count', 'auto_pause', 
            'auto_continue', 'first_point_time',
            'is_gps_open', 'is_network', 'gps_count', 'power_down_count',
            'electric_quantity', 'highest_temperature'
        ];
        $log = common::multiRequest($logParams, 'P');

        if($log['log_type'] && $log['log_content'])
        {
            $log['client'] = $this->client;
            $log['client_type'] = $this->projectId;
            $log['version'] = $this->version;
            $log['uid'] = $this->uid ? $this->uid : 0;
            $log['create_time'] = $this->time;
            $log['create_day'] = strtotime(date('Y-m-d'));
            $log['log_content'] = base64_encode(gzcompress($log['log_content']));

            $this->in_logDb();

            if($this->logDb->insertRow('client_odd', $log))
            {
                $this->result['result'] = 1;
            }
        }
        else
        {
            $_ENV['error']->getErrors(101);
        }
    }

    /**
     * 获取客户端数据
     */
    public function dogetAddClients()
    {
        $count = intval(common::request('count'));
        !$count && $count = 10;

        $clients = $this->in_db('totalDb')->getAll("select * from client_kt where is_push=0 order by cid desc limit {$count}");
        !$clients && $clients = [];

        if($clients)
        {
            foreach($clients as $k => $client)
            {
                $this->in_db('totalDb')->updateRowTable('client_kt', ['cid' => $client['cid'], 'is_push' => 1]);
            }
        }

        $this->result['result'] = $clients;
    }

    /**
     * 查询版本更新信息
     */
    public function dogetAppPackage() {
        $result = array(
            'update'=>'no',
            'updateVersionCode'=>'',
            'apkUrl'=>'',
            'update_log'=>'',
            'md5Hash'=>''
        );
        //渠道号
        $packageChannel = common::request('packageChannel', 'R','');
        $info = $this->db->getRow("select * from r_app_package where status=1");
        if (!$info) {
            $this->result['result']['list'] = $result;
            exit;
        }
        $info['update_txt'] = $info['update_txt']  ?  $info['update_txt'] : '';
        if ($this->versionCode> 0 && ($this->versionCode >= $info['version_num'])) {// 已经更新的不需要更新
            $this->result['result']['list'] = array(
                'update'=>'no',
                'updateVersionCode'=>$info['version_num'],
                'apkUrl'=>$info['file_url'],
                'update_log'=>$info['update_txt'],
                'md5Hash'=>$info['file_hash']
            );
            exit;
        }

        if ($info['channel_type'] == 1) {//全渠道
            if ($info['is_force_update'] == 0) { //不强制更新
                $this->result['result']['list'] = array(
                    'update'=>'suggest',
                    'updateVersionCode'=>$info['version_num'],
                    'apkUrl'=>$info['file_url'],
                    'update_log'=>$info['update_txt'],
                    'md5Hash'=>$info['file_hash']
                );
                exit;
            } else {//强制更新
                if ($this->versionCode > 0 && ($this->versionCode <= $info['force_update_version'])) {//小于强制更新版本都要更新
                     $this->result['result']['list'] = array(
                         'update'=>'force',
                         'updateVersionCode'=>$info['version_num'],
                         'apkUrl'=>$info['file_url'],
                         'update_log'=>$info['update_txt'],
                         'md5Hash'=>$info['file_hash']
                     );
                } else {
                    $this->result['result']['list'] = array(
                        'update'=>'no',
                        'updateVersionCode'=>$info['version_num'],
                        'apkUrl'=>$info['file_url'],
                        'update_log'=>$info['update_txt'],
                        'md5Hash'=>$info['file_hash']
                    );
                    exit;
                }
            }
        } else { //部分渠道
            if (!$packageChannel) {//不需要更新
                $this->result['result']['list'] = array(
                    'update'=>'no',
                    'updateVersionCode'=>$info['version_num'],
                    'apkUrl'=>$info['file_url'],
                    'update_log'=>$info['update_txt'],
                    'md5Hash'=>$info['file_hash']
                );
                exit;
            }
            $arrChannelCode = explode(',',$info['channel_code']);
            if (!in_array($packageChannel,$arrChannelCode)) {//不需要更新
                $this->result['result']['list'] = array(
                    'update'=>'no',
                    'updateVersionCode'=>$info['version_num'],
                    'apkUrl'=>$info['file_url'],
                    'update_log'=>$info['update_txt'],
                    'md5Hash'=>$info['file_hash']
                );
                exit;
            }
            if ($info['is_force_update'] == 0) {//不需要强制更新
                $this->result['result']['list'] = array(
                    'update'=>'suggest',
                    'updateVersionCode'=>$info['version_num'],
                    'apkUrl'=>$info['file_url'],
                    'update_log'=>$info['update_txt'],
                    'md5Hash'=>$info['file_hash']
                );
                exit;
            } else {
                if ($this->versionCode > 0 && ($this->versionCode <= $info['force_update_version'])) {//小于强制更新版本都要更新
                    $this->result['result']['list'] = array(
                        'update'=>'force',
                        'updateVersionCode'=>$info['version_num'],
                        'apkUrl'=>$info['file_url'],
                        'update_log'=>$info['update_txt'],
                        'md5Hash'=>$info['file_hash']
                    );
                } else {
                    $this->result['result']['list'] = array(
                        'update'=>'no',
                        'updateVersionCode'=>$info['version_num'],
                        'apkUrl'=>$info['file_url'],
                        'update_log'=>$info['update_txt'],
                        'md5Hash'=>$info['file_hash']
                    );
                    exit;
                }
            }
        }
    }

    /**
     * 查询版本热修复补丁信息
     */
    public function dogetHotRepair() {
        $patchVersion = (int)common::request('patchVersion', 'G', 0);//最新补丁号
        /*if (!$patchVersion) {
            $this->result['result']['patchList'] = []; exit;
        }*/
        $arrRepairList = $this->db->getAll("select id,patch_version,app_version from r_hot_repair where patch_version > $patchVersion and client_type=$this->projectId and status=1 ORDER BY patch_version desc");
        if (!$arrRepairList) {
            $this->result['result']['patchList'] = []; exit;
        }
        $result =  [];
        $i = 0;
        foreach($arrRepairList as $key=>$val) {
            //过滤不符合的客户端版本号
            if ($val['app_version']) {
                if (!in_array($this->version,explode(',',$val['app_version']))) {
                   continue;
                }
            }
            $result[$val['patch_version']]['patchVersion'] = $val['patch_version'];
            $result[$val['patch_version']]['fileList']  = [];
            //查询补丁
            $plist = $this->db->getAll("select * from r_hot_repair_file where repair_id={$val['id']} and status=0");
            if ($plist) {
                if ($i == 0) { //最大的补丁版本检测次数+1
                    $this->db->update("update  r_hot_repair set check_num=check_num+1 where id={$val['id']}");
                }
                $i++;
                foreach ($plist as $k2=>$v2) {
                    $result[$val['patch_version']]['fileList'][] = array('patchUrl'=>$v2['file_url'],'md5Hash'=>$v2['file_hash']);
                }
            }
        }
        if($result)rsort($result);

//        $result = array(
//            array(
//                'patchVersion'=>1002,
//                'fileList'=>array(
//                    array(
//                        'patchUrl'=>'',
//                        'md5Hash'=>''
//                    )
//                )
//            ),
//            array(
//                'patchVersion'=>1001,
//                'fileList'=>array(
//                    array(
//                        'patchUrl'=>'',
//                        'md5Hash'=>''
//                    )
//                )
//            )
//        );
        $this->result['result']['patchList'] = $result;
        exit;
    }

    /**
     * 增加补丁包更新次数
     */
    public function doIncPatchSaveNum() {
        $strPatchVersion = common::request('strPatchVersion', 'P', 0);//更新的补丁号（|号分隔）
        if (!$strPatchVersion) {
            $this->result['result']['is_success'] = 0;
            exit;
        }
        $arrPatchVersion = array_filter(explode('|',$strPatchVersion));
        if (!$arrPatchVersion) {
            $this->result['result']['is_success'] = 0;
            exit;
        }
        $patchVersion = max($arrPatchVersion);
        $id = $this->db->getOne("select id from r_hot_repair where patch_version='$patchVersion'");
        if (!$id) {
            $this->result['result']['is_success'] = 0;
            exit;
        }
        $r = $this->db->update("update  r_hot_repair set update_num=update_num+1 where id=$id");
        if (!$r) {
            $this->result['result']['is_success'] = 0;
            exit;
        }
        $this->result['result']['is_success'] = 1;

    }
    
    /*
     * 获得关怀文案
     */
    public function dotips(){
        $tips = '';
        $now = time();
        if($this->uid){
            $uid = $this->uid;
            $client_mod = $this->load('client');
            $userInfo = $client_mod->getUserInfo($uid);
            $clientInfo = $client_mod->getClientInfoByUid($uid);
            $lastRun = $client_mod->getLatestRunRecord($uid);
            $thisMonday = date('w',$now)==0 ? strtotime('this monday',$now-86400) : strtotime('this monday');
            if($now - $clientInfo['last_visit'] >= 7*24*3600){
                $tips = $userInfo['nickname']."，欢迎回来，扑妞想你了！";
            }elseif($now - $lastRun['run_time'] >= 3*24*3600){
                $tips = $userInfo['nickname']."，小伙伴们都等着你呢，赶快跑步吧！";
            }elseif($this->db->getOne("select count(*) from r_data_day where `date` between '".date('Ymd',$thisMonday)."' and '".date('Ymd',$now)."' and uid=$uid") >= 4){
                $tips = $userInfo['nickname']."，跑的不错，但是也要注意循序渐进，量力而行！";
            }
        }
        
        if(!$tips){
            /*
            $fakeRunners = $this->redis->hget(REDIS_PREFIX.'SysStatus','fakeRunners');
            $updatetime = (int)$this->redis->hget(REDIS_PREFIX.'SysStatus','updatetime');
            $h = date('H',$now);
            if(!$fakeRunners || (date('H',$updatetime) != $h)){
                if($h>=5 && $h <6){
                    $s=30000;
                    $e=50000;
                }elseif($h>=6 && $h < 8){
                    $s=35000;
                    $e=55000;
                }elseif($h>=8 && $h<11){
                    $s=10000;
                    $e=20000;
                }elseif($h>=11 && $h<14){
                    $s=20000;
                    $e=30000;
                }elseif($h>=14 && $h<17){
                    $s=35000;
                    $e=55000;
                }elseif($h>=17 && $h<22){
                    $s=20000;
                    $e=30000;
                }elseif($h>=22 || $h<5){
                    $s=500;
                    $e=700;
                }
                
                $fakeRunners = rand($s,$e);
                $this->redis->hset(REDIS_PREFIX.'SysStatus','fakeRunners',$fakeRunners);
                $this->redis->hset(REDIS_PREFIX.'SysStatus','updatetime',$now);
            }
            if(isset($userInfo)){
                $tips = $userInfo['nickname'].'，';
            }
            $tips .= "目前有{$fakeRunners}人正在跑步！";
            */
            $tips = '小伙伴们都等着你呢，赶快跑步吧！';
        }
        $this->result['tipsString'] = $tips;
    }
    
    public function dogetBanner(){
        $posi = trim(common::request('posi','G',''));
        if(empty($posi))
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $res = $this->load('banner')->getBanner($posi);
        $result = [];
        $now = time();
        foreach($res as $row){
            if(@$row['startTime'] && strtotime($row['startTime']) > $now){
                continue;
            }
            if(@$row['endTime'] && strtotime($row['endTime']) < $now){
                continue;
            }
            $result[] = $row;
        }
        $this->result['result']['banner'] = $result;
    }
    
    /*
     * 小号列表
     */
    public function dorobotList(){
        $uid = $this->uid;
        $suid = common::request('uid','G',1);
        $user_mod = $this->load('user');
        if(empty($uid)){
            $_ENV['error']->getErrors(201);
            exit;
        }
        if(!$user_mod->canChangeFace($uid)){
            $_ENV['error']->getErrors(903);
            exit;
        }
        
        $start = rand(0,1000);
        //$start = 0;
        
        $this->result['robotList'] = $this->db->getAll("select uid,header,nickname,gender from r_user where uid > '$suid' and is_robot = 1 limit $start,10");
    }
}
